<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper" ref="myElement">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item style="margin-bottom: 20px; margin-top: -30px">
                  <a-divider orientation="left" style="font-weight: bold">
                    <a-icon type="profile" style="margin-right: 8px;color:rgb(13, 158, 243);"></a-icon>基本信息
                  </a-divider>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="数据来源"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-select
                    :style="{ width: selectWidth + 'px' }"
                    allow-clear
                    placeholder="请选择数据来源"
                    v-model="selectedCheckTypes"
                    mode="multiple"
                    @change="handleCheckTypeChange"
                    style="height: 40px; overflow-y: auto;">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="item in CheckTypeList" :key="item.id" :value="item.item">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6" >
                <a-form-item label="检查人员" :labelCol="{ style: 'width:115px' }" :wrapperCol="wrapperCol">
                  <a-input v-model="queryParam.UserName" allow-clear placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
              <a-col :span="8" >
                <a-form-item
                  label="检查时间"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange1" :style="{width: '50%'}" v-model="TimeOn"/>
                  <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange2" :style="{width: '50%'}" v-model="TimeEnd"/>
                </a-form-item>
              </a-col>
              <a-col :span="2" class="search-buttons">
                <a-button type="primary" @click="handleClick" v-if="hasPerm('hdv_qhse_d_compage')">查询</a-button>
              </a-col>
              <a-col :span="2" class="search-buttons">
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24" >
              <a-col :span="6" >
                <a-form-item label="隐患单位" :labelCol="{ style: 'width:115px' }">
                  <a-tree-select
                    :style="{ width: selectWidth + 'px' }"
                    allowClear
                    showSearch
                    style="width:100%;"
                    tree-node-filter-prop="title"
                    v-model="queryParam.DangerOrganizationName"
                    :treeData="QHSEOrganizationTree"
                    v-if="QHSEOrganizationTree.length"
                    @change="handleOrganizationSelectChange"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择隐患单位"
                    :title="queryParam.DangerOrganizationName" />
                </a-form-item>
              </a-col>
              <a-col :span="6" >
                <a-form-item
                  label="检查单位"
                  :labelCol="{ style: 'width:115px' }"
                >
                  <a-tree-select
                    :style="{ width: selectWidth + 'px' }"
                    allowClear
                    showSearch
                    style="width:100%;"
                    tree-node-filter-prop="title"
                    v-model="queryParam.CheckOrganizationName"
                    :treeData="QHSEOrganizationTree1"
                    v-if="QHSEOrganizationTree1.length"
                    @change="onChangeCheckData"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择检查单位"
                    :title="queryParam.CheckOrganizationName" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="数据录入来源"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-select
                    :style="{ width: selectWidth + 'px' }"
                    allow-clear
                    placeholder="请选择数据录入来源"
                    v-model="selectedCheckTypes1"
                    mode="multiple"
                    @change="handleCheckTypeChange1"
                    style="height: 40px; overflow-y: auto;">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="item in enterSyslist" :key="item.id" :value="item.item">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6" >
                <a-form-item label="设备ERP编号" :labelCol="{ style: 'width:115px' }" :wrapperCol="wrapperCol">
                  <a-input v-model="queryParam.ErpNo" allow-clear placeholder="请输入设备ERP编号" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-divider orientation="left" style="font-weight: bold; margin-top: -10px;">
              <a-icon type="info-circle" style="margin-right: 8px;color:rgb(13, 158, 243);"></a-icon> 关键作业信息
            </a-divider>
            <a-row :gutter="24">
              <a-col :span="6">
                <a-form-item
                  label="作业专业"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-select
                    :style="{ width: selectWidth + 'px' }"
                    allow-clear
                    placeholder="请选择作业专业"
                    style="height: 40px; overflow-y: auto;"
                    v-model="selectedWorkSpecialty"
                    @change="handleZYZYSelectChange"
                    mode="multiple"
                    :max-tag-count="7">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="item in QHSEKeyWorkSpecialtyList" :key="item.id" :value="item.specialty" :code="item.specialtyCode">{{
                      item.specialty
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="关键作业类型"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-select
                    :style="{ width: selectWidth + 'px' }"
                    allow-clear
                    placeholder="请选择关键作业类型"
                    style="height: 40px; overflow-y: auto;"
                    v-model="selectedWorkType"
                    @change="handleKeyWorkTypeSelectChange"
                    mode="multiple"
                    :max-tag-count="7">
                    <a-select-option value="全部" v-if="selectedWorkSpecialty && selectedWorkSpecialty.length !== 0">全部</a-select-option>
                    <a-select-option v-for="item in KeyWorkTypeList" :key="item.id" :value="item.workType">{{
                      item.workType
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="作业风险等级"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-select
                    :style="{ width: selectWidth + 'px' }"
                    v-model="selectedWorkRiskList"
                    allow-clear
                    placeholder="请选择作业风险等级"
                    @change="handleRiskSelectChange"
                    mode="multiple"
                    style="height: 40px; overflow-y: auto;">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="item in WorkRiskList" :key="item.id" :value="item.item">{{
                      item.item
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="位置区域"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-select
                    :style="{ width: selectWidth + 'px' }"
                    v-model="selectedLocation"
                    allow-clear
                    placeholder="请选择位置区域"
                    style="height: 40px; overflow-y: auto;"
                    @change="handleLocationSelectChange"
                    mode="multiple"
                    :max-tag-count="6">
                    <a-select-option value="全部" v-if="selectedWorkSpecialty && selectedWorkSpecialty.length !== 0">全部</a-select-option>
                    <a-select-option v-for="item in LocationList" :key="item.id" :value="item.location">{{
                      item.location
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
            </a-row>
            <a-divider orientation="left" style="font-weight: bold; margin-top: -10px;">
              <a-icon type="alert" style="margin-right: 8px;color:rgb(13, 158, 243);"></a-icon> 隐患信息
            </a-divider>
            <a-row :gutter="24">
              <a-col :span="6">
                <a-form-item
                  label="隐患级别"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-select
                    v-model="selectedDangerType"
                    allow-clear
                    mode="multiple"
                    placeholder="请选择隐患级别"
                    style="height: 40px; overflow-y: auto;"
                    @change="handleDangerType">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="(item) in HazardLevelList" :key="item.id" :value="item.item" >{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="隐患类别"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-tree-select
                    :style="{ width: selectWidth + 'px' }"
                    v-model="queryParam.dangerCategory"
                    allowClear
                    showSearch
                    style="scroll: true"
                    tree-node-filter-prop="title"
                    v-if="DangerCategoryTree.length"
                    :treeData="DangerCategoryTree"
                    :defaultExpandAll="true"
                    :replaceFields="replaceFields"
                    @change="handleDangerTypeSelectChange"
                    placeholder="请选择隐患类别"
                    :title="queryParam.dangerCategory"
                  >
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="隐患状态" :labelCol="{ style: 'width:115px' }">
                  <a-select
                    v-model="selectedStatus"
                    allow-clear
                    mode="multiple"
                    placeholder="请选择隐患状态"
                    @change="handleStatus">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="(item) in HazardStatusList" :key="item.id" :value="item.item" >{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="检查方式" :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择检查方式" v-model="queryParam.InspectionMethod">
                    <a-select-option v-for="item in dangerCheckData" :key="item.id" :value="item.item">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="48">
            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-card :bordered="false" style="margin-top: -5px;">
        <a-col :span="2" class="search-buttons" style="margin-left: -5px;">
          <a-button type="primary" @click="handleExport" :disabled="isExported" :loading="batchExportLoading"><a-icon type="export"/>导出</a-button>
        </a-col>
        <a-col :span="4">
          <a-progress
            v-if="batchExportLoading"
            :percent="exportProgress"
            status="active"
          />
        </a-col>
        <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          :alert="null"
          :rowKey="(record) => record.qhseXyDangerId"
          :rowSelection="null"
          bordered
          style="margin-top: 20px"
        >
          <span slot="action" slot-scope="text, record">
            <a-button size="small" style="color:#389e0d;background-color: #f6ffed;border-color: #b7eb8f;">
              <a @click="$refs.DanDetail.edit(record)">
                <a-icon type="file-text" />
                详情
              </a>
            </a-button>
            <a-button size="small" style="color: #1d39c4;background-color: #f0f5ff;border-color: #adc6ff;" v-show="hasPerm('hidden_danger_send')">
              <a @click="handleSend(record)">
                <a-icon type="lock" />
                推送
              </a>
            </a-button>
          </span>
        </s-table>
        <dan-detail ref="DanDetail" @ok="handleOk" />
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
import Vue from 'vue'
import { STable, XCard, XDown, DanDetail } from '@/components'
import { Empty } from 'ant-design-vue'
import { getStartExportToExcel, getExportStatus, getExportEndToExcel } from '@/api/modular/system/QHSEDanger'
import { getQHSECheckTypeList, getQHSEEnterSysList, getDangerCategoryTree, getRiskList, getQHSEDangerComPage, getDataPush } from '@/api/modular/system/QHSEHazardQuery'
import { getQHSEHazardLevelList, getQHSEHazardStatusList } from '@/api/modular/system/QHSEDictionary'
import { getQHSEOrganizationTree, getQHSELocationPage } from '@/api/modular/system/QHSEOrganization'
import { getQHSEKeyWorkSpecialtyList, getQHSEKeyWorkTypePage } from '@/api/modular/system/QHSEKeyWork'
import { getDangerCheckType } from '@/api/modular/system/QHSEDangerinsertManager'
import moment from 'moment'
import { mapGetters } from 'vuex'
export default {
  components: {
    XDown,
    XCard,
    STable,
    DanDetail
  },
  data() {
    return {
      labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
      // 获取参数
      queryParam: {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59'),
        CheckOrganizationId: '',
        DangerOrganizationId: ''
      },
      batchExportLoading: false,
      exportProgress: 0, // 初始化进度为 0
       // 导出参数
      exportParam: {},
      selectedValue: null,
      secondOraName: {
          id: ''
        },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '检查时间',
          dataIndex: 'checkDate',
          customRender: (text, record) => {
            if (record.checkDate) {
              const dateParts = record.checkDate.split('T')[0].split('-')
              return `${dateParts[0]}-${dateParts[1]}-${dateParts[2]}`
            }
            return ''
          }
        },
        {
          title: '检查单位',
          dataIndex: 'checkOrganizationName',
          width: 200,
          customRender: (text) => (
            <a-tooltip title={text}>
              {text.length > 10 ? text.substr(0, 10) + '...' : text}
            </a-tooltip>
          )
        },
        {
          title: '检查人员',
          dataIndex: 'checkName'
        },
        {
          title: '隐患单位',
          dataIndex: 'organizationName',
          width: 200,
          customRender: (text) => (
            <a-tooltip title={text}>
              {text.length > 12 ? text.substr(0, 12) + '...' : text}
            </a-tooltip>
          )
        },
        {
          title: '隐患区域',
          dataIndex: 'location',
          customRender: (text) => (
          <a-tooltip title={text}>
          {text.length > 5 ? text.substr(0, 5) + '...' : text}
          </a-tooltip>
        )
        },
        {
          title: '隐患级别',
          dataIndex: 'dangerType',
          customRender: function(text) {
            if (text === '重大隐患') {
              return <span style={{ color: 'red' }}>{text}</span>
            } else if (text === '较大隐患') {
              return <span style={{ color: 'orange' }}>{text}</span>
            } else {
              return <span style={{ color: 'rgb(227, 227, 70)' }}>{text}</span>
            }
          }
        },
        {
          title: '隐患状态',
          dataIndex: 'status',
          customRender: function(text) {
            if (text === '已整改') {
              return <span style={{ color: 'rgb(34, 173, 34)' }}>{text}</span>
            } else {
              return <span style={{ color: 'red' }}>{text}</span>
            }
          }
        },
        {
          title: '作业项目',
          dataIndex: 'workItem'
        },
        {
          title: '隐患描述',
          dataIndex: 'description',
          customRender: (text) => (
            <a-tooltip title={text}>
              {text.length > 5 ? text.substr(0, 5) + '...' : text}
            </a-tooltip>
          )
        },
        {
          title: 'ERP编号',
          dataIndex: 'erpNo'
        }
      ],
      loadData: (parameter) => {
        return getQHSEDangerComPage(Object.assign(parameter, this.queryParam)).then((res) => {
          this.totleRows = res.data.totalRows
          // console.log('res', res.data.totalRows)
          // console.log(this.queryParam)
          return res.data
        })
      },
      TimeEnd: moment(new Date(), 'YYYY-MM-DD'),
      TimeOn: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
      form: this.$form.createForm(this),
      selectedDangerType: [],
      totleRows: '',
      selectedStatus: [],
      QHSEOrganizationTree: [],
      QHSEOrganizationTree1: [],
      DangerCategoryTree: [],
      QHSEKeyWorkSpecialtyList: [],
      KeyWorkTypeList: [],
      WorkRiskList: [],
      selectedWorkRiskList: [],
      LocationList: [],
      HazardLevelList: [],
      HazardStatusList: [],
      selectedWorkSpecialty: [],
      selectedCheckTypes: [], // 存储选中的数据来源
      selectedCheckTypes1: [],
      selectedWorkType: [],
      CheckTypeList: [], // 数据来源
      enterSyslist: [], // 录入数据来源
      WorkTypeList: [],
      selectedLocation: [],
      dangerCheckData: [],
      defaultExpandedKeys: [],
      ok: false,
      isExported: false,
      task: {},
      status: '',
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'workflowId',
        value: 'id',
        parentId: 'parentId'
      },
      selectWidth: 200,
      queryParam1: {}
    }
  },
  computed: {
      ...mapGetters(['userInfo'])
    },
  //  mounted() {
  //   // const timer = setTimeout(function() {
  //   //   console.log(1) // 3 秒后，打印 1
  //   // }, 3000)
  //  },
  // beforeDestroy() {
  //   window.removeEventListener('resize', this.handleResize)
  // },
  created() {
    this.getQHSEOrganizationTree()
    this.getQHSEOrganizationTree1()
    this.getQHSEHazardLevelList()
    this.getQHSEHazardStatusList()
    this.getQHSECheckTypeList()
    this.getQHSEEnterSysList()
    this.getQHSEKeyWorkSpecialtyList()
    this.getDangerCategoryTree()
    this.getRiskList()
    this.getDangerCheckType()
    this.columns.push({
      title: '操作',
      width: '180px',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    })
    const id = Vue.ls.get('id')
    if (id) {
      this.queryParam.id = id
      // console.log('id1', id)
      this.loadData()
      Vue.ls.remove('id')
    }
  },
  methods: {
    getDangerCheckType() {
      getDangerCheckType().then(res => {
        this.dangerCheckData = res.data
      })
    },
    handleSend (record) {
      this.queryParam1 = {
        id: record.qhseXyDangerId,
        time: record.enterTime,
        orgId: record.secondOrganizationId,
        type: record.dangerType
      }
      getDataPush(this.queryParam1).then(res => {
        console.log('res', res)
      })
    },
    // removeUrlParams(paramsToRemove) {
    //   const url = new URL(window.location.href)
    //   const queryParams = new URLSearchParams(url.search)
    //   // 移除指定的参数
    //   paramsToRemove.forEach(param => queryParams.delete(param))
    //   // 构造新的URL，保留路径和保留的查询参数
    //   const newUrl = `${url.origin}${url.pathname}?${queryParams.toString()}${url.hash}`
    //   // 修改浏览器地址栏中的URL，不刷新页面
    //   window.history.replaceState({}, '', newUrl)
    // },
    handleResize() {
      var myElement = this.$refs.myElement
      if (myElement) {
        var width = myElement.offsetWidth
        this.selectWidth = (width - 12 * 6) / 4 - 115
      }
    },
    handleClick() {
      this.queryParam.id = ''
      if ((!this.TimeOn || !this.TimeEnd) || (this.TimeOn || this.TimeEnd)) {
        this.$refs.table.refresh(true)
        this.exportParam = { ...this.queryParam }
      } else {
        this.$message.warning('请填写完整的时间信息')
      }
    },
    onChange1(date, dateString) {
      // console.log(dateString, date)
      if (this.queryParam.TimeEnd && dateString) {
        if (dateString > this.queryParam.TimeEnd) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD')
        } else {
          this.queryParam.TimeOn = dateString
        }
      } else {
        this.queryParam.TimeOn = dateString
      }
    },
    onChange2(date, dateString) {
      if (this.queryParam.TimeOn && dateString) {
        if (this.queryParam.TimeOn > dateString) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
        }
      } else {
        this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
      }
    },
    // 作业风险等级
    getRiskList() {
      getRiskList().then((res) => {
        this.WorkRiskList = res.data
        // console.log(this.WorkRiskList)
      })
    },
    // 多选作业风险等级
    handleChangeRisk(value) {
      if (value.includes('全部')) {
        // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
        this.queryParam.workRisk = this.WorkRiskList.map(item => item.item)
      } else {
        // 取消选中全部选项，更新 selectedCheckTypes
        this.queryParam.workRisk = value
      }
    },
    // 更改隐患单位
    handleOrganizationSelectChange(val, opt, extra) {
      if (extra.triggerNode === undefined) {
        this.queryParam.DangerOrganizationName = null
        this.queryParam.DangerOrganizationId = null
      } else {
        const option = extra.triggerNode._props.title
        this.queryParam.DangerOrganizationName = option
        this.queryParam.DangerOrganizationId = extra.triggerNode._props.value
      }
    },
    onChangeCheckData(value, label, extra) {
      // console.log(value, label, extra)
      if (extra.triggerNode === undefined) {
        this.queryParam.CheckOrganizationName = null
        this.queryParam.CheckOrganizationId = null
      } else {
        const option = extra.triggerNode._props.title
        this.queryParam.CheckOrganizationName = option
        this.queryParam.CheckOrganizationId = extra.triggerNode._props.value
      }
    },
    handleCheckTypeChange(value) {
      if (value.includes('全部')) {
        // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
        this.selectedCheckTypes = this.CheckTypeList.map(item => item.item)
      }
      this.queryParam.CheckTypes = this.selectedCheckTypes.map(option => option.toString())
    },
    handleCheckTypeChange1(value) {
      if (value.includes('全部')) {
        // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
        this.selectedCheckTypes1 = this.enterSyslist.map(item => item.item)
      }
      this.queryParam.EnterSys = this.selectedCheckTypes1.map(option => option.toString())
    },
    handleDangerTypeSelectChange(val, opt, extra) {
      if (extra.triggerNode === undefined) {
        this.queryParam.dangerCategory = null
      } else {
        const option = extra.triggerNode._props.title
        this.queryParam.dangerCategory = option
      }
    },
    // 类别
    getDangerCategoryTree() {
      getDangerCategoryTree().then((res) => {
        this.formLoading = false
        if (!res.success) {
          this.DangerCategoryTree = []
          return
       }
        this.DangerCategoryTree = res.data
      }).catch((error) => {
        console.error(error) // 打印错误信息
      })
  },
   // 更改作业专业
   handleZYZYSelectChange(value, option) {
      this.KeyWorkTypeList = []
      this.LocationList = []
      this.selectedLocation = []
      this.selectedWorkType = []
      this.queryParam.workType = []
      this.queryParam.location = []

      if (option) {
        let codes = []
        let labels = []
        if (value.includes('全部')) {
          this.selectedWorkSpecialty = this.QHSEKeyWorkSpecialtyList.map(item => item.specialty)
          codes = this.QHSEKeyWorkSpecialtyList.map(item => item.specialtyCode)
          labels = this.QHSEKeyWorkSpecialtyList.map(item => item.specialty)
        } else {
          codes = option.map(item => item.data.attrs.code)
          labels = option.map(item => item.componentOptions.propsData.value)
        }
        // console.log('option:', option)
        // console.log('codes:', codes)
        // console.log('labels:', labels)
        for (let i = 0; i < codes.length; i++) {
          const code = codes[i]
          const label = labels[i]
          getQHSEKeyWorkTypePage({ 'code': code }).then(res => {
            const rowsWithIndex = res.data.rows.map(row => {
              return {
                ...row,
                workType: `${label}-${row.workType}`
              }
            })
            this.KeyWorkTypeList = this.KeyWorkTypeList.concat(rowsWithIndex)
          })
          getQHSELocationPage({ 'code': code }).then(res => {
            const rowsWithIndex = res.data.rows.map(row => {
              return {
                ...row,
                location: `${label}-${row.location}`
              }
            })
            this.LocationList = this.LocationList.concat(rowsWithIndex)
          })
        }
      }
      this.queryParam.workSpecialty = [...this.selectedWorkSpecialty]
    },
    // 关键作业类型
    handleKeyWorkTypeSelectChange(value, option) {
      if (value.includes('全部')) {
        this.selectedWorkType = this.KeyWorkTypeList.map(item => item.workType)
      }
      this.queryParam.workType = [...this.selectedWorkType]
    },
    // 位置区域
    handleLocationSelectChange(value, option) {
      if (value.includes('全部')) {
        this.selectedLocation = this.LocationList.map(item => item.location)
      }
      this.queryParam.location = [...this.selectedLocation]
    },
    // 作业专业
    getQHSEKeyWorkSpecialtyList(text) {
      getQHSEKeyWorkSpecialtyList().then((res) => {
        this.QHSEKeyWorkSpecialtyList = res.data
       })
    },
      // 作业风险等级
    handleRiskSelectChange(value, option) {
      if (value.includes('全部')) {
        this.selectedWorkRiskList = this.WorkRiskList.map(item => item.item)
      }
      this.queryParam.workRisk = [...this.selectedWorkRiskList]
    },
    onChange(date, dateString) {
      this.queryParam.TimeOn = dateString[0]
      this.queryParam.TimeEnd = dateString[1]
    },
    statusFilter (status) {
        // eslint-disable-next-line eqeqeq
        const values = this.QHSEOrgnizationTree.filter(item => item.code === status)
        if (values.length > 0) {
          return values[0].value
        }
    },
    getQHSECheckTypeList(text) {
      getQHSECheckTypeList().then((res) => {
        this.CheckTypeList = res.data // 将后端返回的数据赋值给 CheckTypeList
      //  console.log(this.CheckTypeList)
       })
    },
    getQHSEEnterSysList(text) {
      getQHSEEnterSysList().then((res) => {
        this.enterSyslist = res.data
       })
    },
    getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('tree:', res.data)
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.QHSEOrganizationTree = res.data
        if (res.data.length === 0) {
          this.secondOraName.id = '机关总部'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            this.QHSEOrganizationTree = res.data
          })
        }
        })
      },
      getQHSEOrganizationTree1 () {
      this.secondOraName.id = '安检院'
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('tree:', res.data)
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.QHSEOrganizationTree1 = res.data
        })
      },
    // 隐患级别
    getQHSEHazardLevelList(text) {
      getQHSEHazardLevelList().then((res) => {
        this.HazardLevelList = res.data
      })
    },
    // 多选隐患级别
    handleDangerType(value) {
      if (value.includes('全部')) {
        // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
        this.selectedDangerType = this.HazardLevelList.map(item => item.item)
        console.log(this.selectedDangerType)
      } // 取消选中全部选项，更新 selectedCheckTypes
        this.queryParam.dangerType = [...this.selectedDangerType]
    },
    // 隐患状态
    getQHSEHazardStatusList(text) {
      getQHSEHazardStatusList().then((res) => {
        this.HazardStatusList = res.data
      })
    },
    // 多选隐患状态
    handleStatus(value, option) {
      if (value.includes('全部')) {
        // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
        this.selectedStatus = this.HazardStatusList.map(item => item.item)
      }
        // 取消选中全部选项，更新 selectedCheckTypes
        this.queryParam.status = [...this.selectedStatus]
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    getStartExportToExcel() {
      getStartExportToExcel(this.queryParam).then(res => {
        this.task.Id = res.taskId
      })
    },
    getExportStatus() {
      return getExportStatus(this.task).then(res => {
        this.status = res.status
      })
    },
    handleExport(parameter) {
      this.isExported = true
      if (this.totleRows >= 30000) {
        this.$message.warning('一次性导出的数据不能超过30000条!')
        this.isExported = false
      } else {
      this.getStartExportToExcel()
      this.batchExportLoading = true
      this.exportProgress = 0 // 重置进度
      this.exportParam = { ...this.queryParam }
      // const interval =
      setInterval(() => {
        if (this.exportProgress < 90) { // 进度最高到 90%，剩下的 10% 在下载完成时更新
          this.exportProgress += 10
        }
      }, 500)
       // 每 5 秒轮询状态
       const statusInterval = setInterval(() => {
        this.getExportStatus().then(() => {
          if (this.status === 'completed') {
            // 清除进度定时器，确保定时器被清除
            clearInterval(statusInterval)
            // 开始执行 getExportToExcel
            getExportEndToExcel(this.task)
            .then(response => {
              console.log(response)
              // clearInterval(interval)
              this.exportProgress = 100 // 导出完成后，设置进度为 100%
              // 创建下载链接
              const downloadLink = document.createElement('a')
              downloadLink.href = window.URL.createObjectURL(response.data)
              downloadLink.download = '隐患_' + new Date().toISOString() + '.xlsx'
              downloadLink.target = '_blank'
              // 停止加载状态
              downloadLink.addEventListener('click', () => {
                this.batchExportLoading = false
              })
              downloadLink.click() // 触发下载
              this.isExported = false
            })
            .catch(error => {
              console.error('下载失败:', error)
              this.batchExportLoading = false
              this.isExported = false
            })
          }
        }).catch(error => {
          console.error('状态获取失败:', error)
          clearInterval(statusInterval) // 出现错误时，也要清除定时器
          this.isExported = false
          // clearInterval(interval)
        })
      }, 5000) // 每 5 秒轮询一次状态
      // clearInterval(interval)
      }
    },
    reset() {
      this.queryParam = {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD')
      }
      this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
      this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
      this.selectedCheckTypes = []
      this.selectedWorkType = []
      this.selectedRisk = []
      this.selectedWorkRiskList = []
      this.selectedPosition = []
      this.selectedLocation = []
      this.selectedDangerType = []
      this.selectedWorkSpecialty = []
      this.selectedStatus = []
      this.exportParam = {}
      this.LocationList = []
      this.KeyWorkTypeList = []
    }
  }
}
</script>
<style lang="less" scoped>
  /deep/.ant-table-tbody tr:nth-child(2n) {
    background-color:#f5f5f5;
  }
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
.scrollable-select {
  max-height: 200px; /* 根据需要设置最大高度 */
  overflow-y: auto;
}
</style>
